using System;
using System.IO;
using Common.Infrastructure;
using Core.Infrastructure.StructureMap;
using GemBox.Spreadsheet;
using NSBus.Server.Initialization;
using NSBus.Server.Initialization.Automapper;
using NServiceBus;
using NServiceBus.Features;
using Sanelib.Initialization;
using StructureMap;
/*
    This class configures this endpoint as a Server. More information about how to configure the NServiceBus host
    can be found here: http://particular.net/articles/the-nservicebus-host
*/

namespace NSBus.Server
{
    public class NBusServerEndPoint : IWantCustomInitialization, IWantToRunWhenBusStartsAndStops, IConfigureThisEndpoint, AsA_Server
    {
        public void Init()
        {
            CheckConfigurations();

            ObjectFactory.Initialize(x => x.Scan(scan =>
            {
                scan.TheCallingAssembly();
                scan.AssemblyContainingType<SanelibRegistry>();
                scan.AssemblyContainingType<CommonRegistry>();
                scan.AssemblyContainingType<CoreRegistry>();
                scan.AssemblyContainingType<NBusServerRegistry>();
                scan.WithDefaultConventions();
                scan.LookForRegistries();
            }));

            AutoMapperConfiguration.Configure(ObjectFactory.GetInstance);

            SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

            Configure.Serialization.Json();
            Configure.Transactions.Enable();
            Configure.Features.Enable<Sagas>();

            Configure.With()
                .DefineEndpointName("SanelibService")
                .StructureMapBuilder(ObjectFactory.Container)
                .DefiningCommandsAs(t => t.Namespace != null && t.Namespace.StartsWith("NSBus.Dto.Commands"))
                .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("NSBus.Dto.Events"))
                .DefiningMessagesAs(t => t.Namespace != null && t.Namespace.StartsWith("NSBus.Dto.Mesages"))
                .RavenPersistence()
                .RavenSubscriptionStorage()
                .RavenSagaPersister()
                .UseRavenTimeoutPersister()
                .UseRavenGatewayPersister()
                .PurgeOnStartup(false)
                .UnicastBus().ImpersonateSender(false);           
        }

        public void Start()
        {
            Console.WriteLine("Service Start");
        }

        public void Stop()
        {
            Console.WriteLine("Stop Service Called");
        }

        public bool CheckConfigurations()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "\\";

            var srcPath = path + "..\\Deployment\\Configs";

            if (!Directory.Exists(srcPath))
            {
                srcPath = path + "..\\..\\..\\Deployment\\Configs";
                if (!Directory.Exists(srcPath))
                {
                    throw new Exception("Src config directory not exist at " + srcPath);
                }
            }

            var destPath = path + "Configs\\";

            Console.WriteLine("Source config path: " + srcPath);
            Console.WriteLine("Dest config path: " + destPath);

            System.Threading.Thread.Sleep(3000);

            if (!Directory.Exists(destPath)) Directory.CreateDirectory(destPath);

            var configDirectory = new DirectoryInfo(srcPath);

            var configs = configDirectory.GetFiles("*.xml");
            foreach (var fileInfo in configs)
            {
                var destFileName = destPath + fileInfo.Name;
                fileInfo.CopyTo(destFileName, true);
            }

            return true;
        }
    }
}
